package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架
 * 每晚三点 上架最近三天需要秒杀的商品
 */
@Component
@Slf4j
public class SecKillSchedule {

    @Autowired
    private SecKillService secKillService;

    @Autowired
    private RedissonClient redissonClient;

    private final String upload_lock = "seckill:upload:lock";

    @Async
    @Scheduled(cron = "0 3 * * * ?")
    public void uploadSeckillLasted3Days() {
        log.info("上架商品");
        RLock lock = redissonClient.getLock(upload_lock);
        try{
            lock.lock(10, TimeUnit.SECONDS);
            secKillService.uploadSeckillLasted3Days();
        }finally {
            lock.unlock();
        }


    }

}
